package com.mayikt;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Author: maplefire
 * @Description:
 * @Date: 2022/11/01 14:22
 */

// 读写锁 jvm内置缓存
public class Test03 {
    private volatile Map caChe = new HashMap<String, String>();
    // 读写锁
    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.WriteLock writeLock = rwl.writeLock();// 写入锁
    private ReentrantReadWriteLock.ReadLock readLock = rwl.readLock();// 读取锁

    // 写入元素
    public void put(String key, String value) {

        try {
            writeLock.lock();
            System.out.println("写入put方法 key:" + key + ", value:" + value + ",开始");
            Thread.sleep(50);
            caChe.put(key, value);
            System.out.println("写入put方法 key:" + key + ", value:" + value + ",结束");
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            writeLock.unlock();
        }
    }

    // 读取元素
    public String get(String key) {
        try {
            readLock.lock();
            System.out.println("读取key:" + key + ",开始");
            //Thread.sleep(50);
            String value = (String) caChe.get(key);
            System.out.println("读取key:" + key + ",结束");
            return value;
        } catch (Exception e) {
            return null;
        } finally {
            readLock.unlock();
        }
    }

    public static void main(String[] args) {
        final Test03 test03 = new Test03();
        // 写线程
        Thread t1 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    test03.put(i + "", i + "");
                }
            }
        });
        // 读线程
        Thread t2 = new Thread(new Runnable() {
            public void run() {
                for (int i = 0; i < 10; i++) {
                    test03.get(i + "");
                }
            }
        });
        t1.start();
        t2.start();
    }
}